import 'dart:async';
import 'dart:convert';
import 'dart:ffi';

import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class CustomRuleActionPage extends StatefulWidget {
  const CustomRuleActionPage({super.key});

  @override
  State<CustomRuleActionPage> createState() => _CustomRuleActionPageState();
}

class _CustomRuleActionPageState extends State<CustomRuleActionPage> {

  Timer? _timer;


  late List<Map<String, dynamic>> inputFields = [];
  late List<String> inputFieldsBack = [];
  late var barcode = TextEditingController();
  late var barcodeTemp = "";
  late var baseUrl = "";
  late var station = "";

  // 初始化本地设置
  Future<void> initLocal() async {
    barcode.text = "";
    final prefs = await SharedPreferences.getInstance();
    var ip1 = prefs.getString("ip") ?? "";
    var port1 = prefs.getString("port") ?? "";
    var station1 = prefs.getString("station") ?? "";
    baseUrl = "http://$ip1:$port1";
    print(baseUrl);
    station = station1;
    getData(1);
  }

  // 正确的方法定义
  Future<void> getData(int flag) async {
    try {
      final response = await http.get(
        Uri.parse("$baseUrl/api/custRule/getRules?use=$station"),
      );

      if (response.statusCode == 200) {
        // 处理成功响应
        final result = json.decode(response.body)["result"];
        if (flag == 1) {
          for (var item in result) {
            Map<String, dynamic> temp = {};
            temp["value"] = TextEditingController(text: "");
            temp["name"] = item["ruleName"];
            temp["ruleContent"] = item["ruleContent"];
            temp["ruleLength"] = item["ruleLength"];
            temp["rulePlan"] = item["rulePlan"];
            inputFields.add(temp);
            inputFieldsBack.add("");
          }
        } else {
          if (result.length > inputFields.length) {
            for (int i = 0; i < (result.length - inputFields.length); i++) {
              Map<String, dynamic> temp = {};
              temp["value"] = TextEditingController(text: "");
              temp["name"] = result[i]["ruleName"];
              temp["ruleContent"] = result[i]["ruleContent"];
              temp["ruleLength"] = result[i]["ruleLength"];
              temp["rulePlan"] = result[i]["rulePlan"];
              inputFields.add(temp);
              inputFieldsBack.add("");
            }
            return;

          } else if (result.length < inputFields.length) {
            inputFields.clear();
            inputFieldsBack.clear();
            for (int i = 0; i < result.length; i++) {
              Map<String, dynamic> temp = {};
              temp["value"] = TextEditingController(text: "");
              temp["name"] = result[i]["ruleName"];
              temp["ruleContent"] = result[i]["ruleContent"];
              temp["ruleLength"] = result[i]["ruleLength"];
              temp["rulePlan"] = result[i]["rulePlan"];
              inputFields.add(temp);
              inputFieldsBack.add("");
            }
            FocusScope.of(context).requestFocus(_focusNode.children.first);

            return;
          }
          for (int i = 0; i < result.length; i++) {
            inputFields[i]["name"] = result[i]["ruleName"];
            inputFields[i]["ruleContent"] = result[i]["ruleContent"];
            inputFields[i]["ruleLength"] = result[i]["ruleLength"];
            inputFields[i]["rulePlan"] = result[i]["rulePlan"];
          }
        }
        setState(() {});
      } else {
        // 处理错误
        print("请求失败: ${response.statusCode}");
      }
    } catch (e) {
      print("请求异常: $e");
    }
  }

  Future<void> handleSendDataClick() async {
    if (barcode.text.isEmpty) {
      TDToast.showFail("产品条码不能为空", context: context);
      return;
    }
    for (int i = 0; i < inputFields.length; i++) {
      var item = inputFields[i];
      if (!item["value"].text.startsWith(item["ruleContent"])) {
        TDToast.showText("${item["name"]}的开始内容与设置的配方内容不匹配!", context: context);
        return;
      }
      if (!(item["value"].text.length == int.parse(item["ruleLength"]))) {
        TDToast.showText("${item["name"]}的条码长度与设置的配方长度不匹配!", context: context);
        return;
      }
    }
    generateCustRuleData();
  }

  Future<void> generateCustRuleData() async   {
    try {
      final res = await http.get(
        Uri.parse(
          "$baseUrl/api/custRuleData/getCustRuleDatas?barcode=${barcode.text}",
        ),
      );
      List<dynamic> data = json.decode(res.body)["result"];
      if (data.isEmpty) {
        print("isEmpty 新增数据!!!");
        // 1. 遍历 inputFields，给每个元素添加 location 字段
        var temp = inputFields.map((item) {
          // 避免直接修改原数据，创建一个新的 Map
          return {
            ...item, // 保留原有字段
            "value": item["value"].text,
            'location': station, // 新增 location 字段
          };
        }).toList();
        // 创建新的数据
        final Map<String, dynamic> requestBody = {
          "barcode": barcode.text.replaceAll("\n", ""),
          "planName": inputFields[0]["rulePlan"],
          "location": station,
          "data": jsonEncode({station: temp}), // 将数据转换为JSON字符串
        };
        final response = await http.post(
          Uri.parse("$baseUrl/api/custRuleData/generateCustRuleData"),
          headers: {'Content-Type': 'application/json'}, // 添加正确的header
          body: jsonEncode(requestBody), // 将整个body转换为JSON字符串
        );
        print(requestBody);
        if (response.statusCode == 200) {
          TDToast.showSuccess("添加成功", context: context);
          for (int i = 0; i < inputFields.length; i++) {
            inputFields[i]["value"].clear();
            barcode.clear();
          }
          setState(() {});
          return;
        }
        TDToast.showFail("添加失败", context: context);
      } else {
        print("isNotEmpty 更新数据!!!");

        data[0]["data"] = jsonDecode(data[0]["data"]);
        final item = data[0];
        // 1. 遍历 inputFields，给每个元素添加 location 字段
        var temp = inputFields.map((item) {
          // 避免直接修改原数据，创建一个新的 Map
          return {
            ...item, // 保留原有字段
            "value": item["value"].text,
            'location': station, // 新增 location 字段
          };
        }).toList();
        final Map<String, dynamic> requestBody = {
          "barcode": barcode.text.replaceAll("\n", ""),
          "planName": inputFields[0]["rulePlan"],
          "location": station,
          "data": jsonEncode({...item["data"], station: temp}), // 将数据转换为JSON字符串
        };
        final patchRes = await http.patch(
          headers: {'Content-Type': 'application/json'}, // 确保添加这个
          Uri.parse("$baseUrl/api/custRuleData/patchCustRuleData"),
          body: jsonEncode(requestBody),
        );
        final pResult = json.decode(patchRes.body)["result"];
        if (pResult) {
          TDToast.showSuccess("更新成功!", context: context);
        }
        for (int i = 0; i < inputFields.length; i++) {
          inputFields[i]["value"].clear();
          barcode.clear();
        }
        setState(() {});
      }
      FocusScope.of(context).requestFocus(_focusNode.children.first);

    } catch (e) {
      print("objecterror --------" + e.toString());
    }
  }

  final _focusNode = FocusNode();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initLocal();
    Future.delayed(Duration(milliseconds: 100), () {
      FocusScope.of(context).requestFocus(_focusNode.children.first);
    });
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      getData(2);
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            // 顶部固定输入框（不可滚动）
            SizedBox(
              width: 620,
              child: KeyboardListener(
                focusNode: _focusNode,
                onKeyEvent: (e) async {
                  try {
                    print(e.logicalKey.hashCode);
                    print(e.character == null);
                    print("");
                    print(e.character!.toString());
                    if (e.character != null) {
                      barcodeTemp += e.character!;
                      barcode.text = "";
                    }
                    if (e.logicalKey == LogicalKeyboardKey.enter &&
                        barcodeTemp.isNotEmpty) {
                      barcode.text = barcodeTemp.replaceAll("\n", "");
                      barcodeTemp = "";

                      final res = await http.get(
                        Uri.parse(
                          "$baseUrl/api/custRuleData/getCustRuleDatas?barcode=${barcode.text}",
                        ),
                      );

                      var result = json.decode(res.body);
                      var data = json.decode(result["result"][0]["data"]);

                      print("$baseUrl/api/custRuleData/getCustRuleDatas?barcode=${barcode.text}");
                      print(data.containsKey(station));

                      if (data.containsKey(station) && data[station] is List) {
                        // 安全操作
                        for (int i = 0; i < inputFields.length; i++) {
                          for (int j = 0; j < data[station].length; j++) {
                            if (inputFields[i]["name"] ==
                                data[station][j]["name"]) {
                              inputFields[i]["value"].text =
                                  data[station][j]["value"];
                            }
                          }
                        }
                      }
                    }
                  } catch (e) {
                    print(e.toString());
                  }
                },
                child: TextField(
                  controller: barcode,
                  keyboardType: TextInputType.none,
                  onEditingComplete: () {},
                  readOnly: true,
                  textInputAction: TextInputAction.none, // 阻止默认的键盘动作
                  decoration: InputDecoration(
                    suffixIcon: barcode != ""
                        ? IconButton(
                            onPressed: () {
                              for (int i = 0; i < inputFields.length; i++) {
                                inputFields[i]["value"].clear();
                              }
                              barcode.clear();
                            },
                            icon: Icon(Icons.clear),
                          )
                        : null,
                    labelText: "产品条码",
                    border: OutlineInputBorder(),
                    labelStyle: TextStyle(
                      fontSize: 20, // 标签字体调小
                    ),
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 20,
                      vertical: 25, // 关键：垂直内边距归零
                    ),
                  ),
                ),
              ),
            ),
            const SizedBox(height: 10),

            // 动态生成的可滚动区域
            Expanded(
              child: Scrollbar(
                // 关键组件
                thumbVisibility: true, // 始终显示滚动条（Flutter 2.3+）
                trackVisibility: true, // 显示滚动轨道（可选）
                thickness: 8, // 滚动条宽度
                radius: Radius.circular(4), // 圆角
                child: GridView.builder(
                  padding: EdgeInsets.zero,
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 2,
                    childAspectRatio: 5, // 关键参数：值越大高度越小
                    mainAxisSpacing: 4, // 行间距
                    crossAxisSpacing: 20, // 列间距
                  ),
                  itemCount: inputFields.length,
                  itemBuilder: (context, index) {
                    return Container(
                      margin: EdgeInsets.only(top: 10),
                      child: KeyboardListener(
                        focusNode: FocusNode(),
                        onKeyEvent: (e) {
                          if (e.character != null) {
                            inputFieldsBack[index] += e.character!;
                            inputFields[index]["value"].text = "";
                          }
                          if (e.logicalKey == LogicalKeyboardKey.enter &&
                              inputFieldsBack[index].isNotEmpty) {
                            inputFields[index]["value"].text =
                                inputFieldsBack[index].replaceAll("\n", "");
                            inputFieldsBack[index] = "";
                          }
                        },
                        child: TextField(
                          controller: inputFields[index]['value'],
                          onEditingComplete: () {},
                          readOnly: true,
                          keyboardType: TextInputType.none,
                          textInputAction: TextInputAction.none, // 阻止默认的键盘动作
                          decoration: InputDecoration(
                            labelText: inputFields[index]['name'],
                            border: OutlineInputBorder(),
                            contentPadding: const EdgeInsets.symmetric(
                              horizontal: 20,
                              vertical: 25, // 关键：垂直内边距归零
                            ),
                            isDense: true, // 启用紧凑模式
                            labelStyle: TextStyle(
                              fontSize: 20, // 标签字体调小
                            ),
                            suffixIcon: inputFields[index]["value"].text != ""
                                ? IconButton(
                                    onPressed: () {
                                      inputFields[index]["value"].text = "";
                                    },
                                    icon: Icon(Icons.clear),
                                  )
                                : null,
                          ),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
            // 底部固定按钮（不可滚动）
            SizedBox(
              width: 360,
              child: ElevatedButton(
                onPressed: () {
                  handleSendDataClick();
                },
                child: Text("保存信息", style: TextStyle(fontSize: 20)),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
